/**
 * SEO分析服务
 * 提供关键词分析、SEO评分、优化建议等功能
 */

import type { SEOAnalysis, Keyword } from '@/stores/optimizer.store';

/**
 * SEO分析请求
 */
interface SEOAnalyzeRequest {
  content: string;
  title?: string;
  targetKeywords?: string[];    // 目标关键词
}

/**
 * Meta标签生成请求
 */
interface MetaTagsRequest {
  content: string;
  title?: string;
  maxTitleLength?: number;      // 最大标题长度
  maxDescLength?: number;       // 最大描述长度
}

/**
 * 关键词建议请求
 */
interface KeywordSuggestionsRequest {
  topic: string;
  industry?: string;
  targetAudience?: string;
}

/**
 * SEO分析服务类
 */
class SEOAnalyzerService {
  private baseUrl: string;

  constructor() {
    this.baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  }

  /**
   * 分析SEO
   */
  async analyzeSEO(content: string, title?: string, targetKeywords?: string[]): Promise<SEOAnalysis> {
    console.log('🔍 [SEOAnalyzer] Analyzing SEO...', { length: content.length });

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/seo-analysis`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ content, title, targetKeywords } as SEOAnalyzeRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ [SEOAnalyzer] SEO analysis complete');

      return this.transformSEOAnalysis(data);
    } catch (error) {
      console.error('❌ [SEOAnalyzer] SEO analysis failed:', error);
      // 返回Mock数据
      return this.generateMockSEOAnalysis(content, title);
    }
  }

  /**
   * 提取关键词
   */
  async extractKeywords(content: string, count: number = 20): Promise<Keyword[]> {
    console.log('🔑 [SEOAnalyzer] Extracting keywords...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/extract-keywords`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ content, count }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return data.keywords.map((k: any) => this.transformKeyword(k));
    } catch (error) {
      console.error('❌ [SEOAnalyzer] Keyword extraction failed:', error);
      return this.extractMockKeywords(content, count);
    }
  }

  /**
   * 生成Meta标签
   */
  async generateMetaTags(
    content: string,
    title?: string,
    options?: { maxTitleLength?: number; maxDescLength?: number }
  ): Promise<{
    title: string;
    description: string;
    keywords: string[];
  }> {
    console.log('🏷️ [SEOAnalyzer] Generating meta tags...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/meta-tags`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content,
          title,
          maxTitleLength: options?.maxTitleLength || 60,
          maxDescLength: options?.maxDescLength || 160,
        } as MetaTagsRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return {
        title: data.title,
        description: data.description,
        keywords: data.keywords || [],
      };
    } catch (error) {
      console.error('❌ [SEOAnalyzer] Meta tag generation failed:', error);
      return this.generateMockMetaTags(content, title);
    }
  }

  /**
   * 分析关键词密度
   */
  async analyzeKeywordDensity(content: string, keywords: string[]): Promise<Map<string, {
    count: number;
    density: number;
    positions: number[];
    distribution: {
      title: number;
      firstParagraph: number;
      body: number;
      lastParagraph: number;
    };
  }>> {
    console.log('📊 [SEOAnalyzer] Analyzing keyword density...');

    const result = new Map();

    for (const keyword of keywords) {
      const regex = new RegExp(keyword, 'gi');
      const matches = [...content.matchAll(regex)];
      const count = matches.length;
      const density = (count / content.length) * 100;

      // 分析分布
      const paragraphs = content.split('\n\n');
      const firstPara = paragraphs[0] || '';
      const lastPara = paragraphs[paragraphs.length - 1] || '';

      result.set(keyword, {
        count,
        density,
        positions: matches.map(m => m.index || 0),
        distribution: {
          title: (content.slice(0, 100).match(regex) || []).length,
          firstParagraph: (firstPara.match(regex) || []).length,
          body: count - (firstPara.match(regex) || []).length - (lastPara.match(regex) || []).length,
          lastParagraph: (lastPara.match(regex) || []).length,
        },
      });
    }

    return result;
  }

  /**
   * 获取关键词建议
   */
  async getKeywordSuggestions(
    topic: string,
    industry?: string,
    targetAudience?: string
  ): Promise<{
    primary: string[];
    secondary: string[];
    longTail: string[];
    competitor: string[];
  }> {
    console.log('💡 [SEOAnalyzer] Getting keyword suggestions...');

    try {
      const response = await fetch(`${this.baseUrl}/api/v1/optimizer/keyword-suggestions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ topic, industry, targetAudience } as KeywordSuggestionsRequest),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return {
        primary: data.primary || [],
        secondary: data.secondary || [],
        longTail: data.long_tail || [],
        competitor: data.competitor || [],
      };
    } catch (error) {
      console.error('❌ [SEOAnalyzer] Keyword suggestions failed:', error);
      return this.generateMockKeywordSuggestions(topic);
    }
  }

  /**
   * 检查标题SEO
   */
  async checkTitleSEO(title: string, targetKeywords?: string[]): Promise<{
    score: number;
    length: number;
    hasKeyword: boolean;
    suggestions: string[];
  }> {
    console.log('📝 [SEOAnalyzer] Checking title SEO...');

    const length = title.length;
    let score = 50;
    const suggestions: string[] = [];

    // 长度检查
    if (length >= 50 && length <= 60) {
      score += 20;
    } else if (length < 50) {
      suggestions.push('标题过短，建议增加到50-60字符');
      score -= 10;
    } else {
      suggestions.push('标题过长，建议控制在60字符以内');
      score -= 10;
    }

    // 关键词检查
    let hasKeyword = false;
    if (targetKeywords && targetKeywords.length > 0) {
      hasKeyword = targetKeywords.some(kw => title.includes(kw));
      if (hasKeyword) {
        score += 30;
      } else {
        suggestions.push('标题中缺少目标关键词');
        score -= 20;
      }
    }

    return {
      score: Math.max(0, Math.min(100, score)),
      length,
      hasKeyword,
      suggestions,
    };
  }

  /**
   * 分析标题结构
   */
  analyzeHeadingStructure(content: string): SEOAnalysis['headingStructure'] {
    const headings: SEOAnalysis['headingStructure'] = [];
    const lines = content.split('\n');

    lines.forEach((line, index) => {
      const trimmed = line.trim();

      // Markdown格式
      if (trimmed.startsWith('######')) {
        headings.push({ level: 'H6', text: trimmed.replace(/^#+\s*/, ''), position: index });
      } else if (trimmed.startsWith('#####')) {
        headings.push({ level: 'H5', text: trimmed.replace(/^#+\s*/, ''), position: index });
      } else if (trimmed.startsWith('####')) {
        headings.push({ level: 'H4', text: trimmed.replace(/^#+\s*/, ''), position: index });
      } else if (trimmed.startsWith('###')) {
        headings.push({ level: 'H3', text: trimmed.replace(/^#+\s*/, ''), position: index });
      } else if (trimmed.startsWith('##')) {
        headings.push({ level: 'H2', text: trimmed.replace(/^#+\s*/, ''), position: index });
      } else if (trimmed.startsWith('#')) {
        headings.push({ level: 'H1', text: trimmed.replace(/^#+\s*/, ''), position: index });
      }

      // HTML格式
      const htmlMatch = trimmed.match(/^<(h[1-6])>(.*?)<\/h[1-6]>/i);
      if (htmlMatch) {
        headings.push({
          level: htmlMatch[1].toUpperCase() as any,
          text: htmlMatch[2],
          position: index,
        });
      }
    });

    return headings;
  }

  /**
   * 转换SEO分析格式
   */
  private transformSEOAnalysis(data: any): SEOAnalysis {
    return {
      keywords: (data.keywords || []).map((k: any) => this.transformKeyword(k)),
      titleScore: data.title_score || 0,
      titleLength: data.title_length || 0,
      titleSuggestion: data.title_suggestion,

      metaDescription: data.meta_description,
      metaDescriptionScore: data.meta_description_score || 0,

      headingStructure: data.heading_structure || [],

      internalLinks: data.internal_links || 0,
      externalLinks: data.external_links || 0,
      imageCount: data.image_count || 0,
      imagesWithAlt: data.images_with_alt || 0,

      keywordDistribution: data.keyword_distribution || {
        title: 0,
        firstParagraph: 0,
        body: 0,
        lastParagraph: 0,
      },

      recommendations: data.recommendations || [],
      competitorKeywords: data.competitor_keywords || [],
      longTailKeywords: data.long_tail_keywords || [],
    };
  }

  /**
   * 转换关键词格式
   */
  private transformKeyword(data: any): Keyword {
    return {
      word: data.word,
      count: data.count,
      density: data.density,
      positions: data.positions || [],
      importance: data.importance || 'tertiary',
    };
  }

  /**
   * 生成Mock SEO分析
   */
  private generateMockSEOAnalysis(content: string, title?: string): SEOAnalysis {
    const keywords = this.extractMockKeywords(content, 10);

    return {
      keywords,

      titleScore: 65,
      titleLength: title?.length || 0,
      titleSuggestion: '建议标题长度控制在50-60字符，并包含核心关键词',

      metaDescription: '本文深入探讨AI写作技术如何提升内容创作效率，包括智能优化、SEO分析等核心功能...',
      metaDescriptionScore: 70,

      headingStructure: this.analyzeHeadingStructure(content),

      internalLinks: 2,
      externalLinks: 3,
      imageCount: 1,
      imagesWithAlt: 0,

      keywordDistribution: {
        title: 1,
        firstParagraph: 2,
        body: keywords[0]?.count - 3 || 0,
        lastParagraph: 1,
      },

      recommendations: [
        '标题中添加核心关键词',
        '首段关键词密度较低，建议增加到2-3%',
        '添加更多内部链接，建议5-8个',
        '为图片添加Alt文本，提升SEO',
        '优化Meta描述，包含核心关键词',
        '建议添加H2、H3标签优化结构',
      ],

      competitorKeywords: [
        '智能写作',
        'AI文章生成',
        '自动化创作',
        '写作助手',
      ],

      longTailKeywords: [
        'AI写作工具如何提升效率',
        '内容创作AI技术应用',
        '智能写作平台推荐',
      ],
    };
  }

  /**
   * 提取Mock关键词
   */
  private extractMockKeywords(content: string, count: number): Keyword[] {
    // 简单的关键词提取（基于词频）
    const words = content.match(/[\u4e00-\u9fa5]{2,}|[a-zA-Z]{3,}/g) || [];
    const wordFreq = new Map<string, number>();

    words.forEach(word => {
      wordFreq.set(word, (wordFreq.get(word) || 0) + 1);
    });

    const sortedWords = Array.from(wordFreq.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, count);

    return sortedWords.map(([word, freq], index) => ({
      word,
      count: freq,
      density: (freq / content.length) * 100,
      positions: [],
      importance: index < 3 ? 'primary' : index < 8 ? 'secondary' : 'tertiary',
    }));
  }

  /**
   * 生成Mock Meta标签
   */
  private generateMockMetaTags(content: string, title?: string): {
    title: string;
    description: string;
    keywords: string[];
  } {
    const keywords = this.extractMockKeywords(content, 5);

    return {
      title: title || '智能写作平台 - AI助力内容创作',
      description: content.slice(0, 155) + '...',
      keywords: keywords.map(k => k.word),
    };
  }

  /**
   * 生成Mock关键词建议
   */
  private generateMockKeywordSuggestions(topic: string): {
    primary: string[];
    secondary: string[];
    longTail: string[];
    competitor: string[];
  } {
    return {
      primary: [
        `${topic}`,
        `${topic}技术`,
        `${topic}应用`,
      ],
      secondary: [
        `${topic}优势`,
        `${topic}发展`,
        `${topic}趋势`,
        `${topic}案例`,
      ],
      longTail: [
        `${topic}如何提升效率`,
        `${topic}最佳实践`,
        `${topic}完整指南`,
        `${topic}2024年趋势`,
      ],
      competitor: [
        `${topic}工具`,
        `${topic}平台`,
        `${topic}服务`,
      ],
    };
  }
}

export const seoAnalyzerService = new SEOAnalyzerService();
